
import json
import re
import uuid

import pytz
from django.db.models import Max
from django.http import HttpResponse
from django.shortcuts import render, redirect

import datetime
import time

from django_redis import get_redis_connection

from Bug import settings
from utils.alipay import AliPay
from web import models


def payment(request, policy_id):
    """ 支付页面"""
    user_mobile_phone= request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()

    if user_object:  # 没有公司登陆

        user_trade = models.trade.objects.filter(org_id=user_object.org_id).filter(status="2").order_by(
            "-crdate").first()

        """订单已经生成的情况"""
        conn = get_redis_connection()
        key = 'payment_{}'.format(request.tracer.user.mobile_phone)
        context_string = conn.get(key)
        if context_string:  # 如果订单存在
            context = json.loads(context_string.decode('utf-8'))
            if context['policy_id'] == "1":
                type = "￥10/月"
            elif context['policy_id'] == "2":
                type = "￥38/季"
            elif context['policy_id'] == "3":
                type = "￥110/年"
            else:
                type = "错误"
            dd = {"org_id": context['tradeid'], "type": type, "number": context['number'], "endtime": context['end'],
                  "money": context['money']}
            return render(request, 'web/payment.html', {"dd": dd})
        now = datetime.datetime.now()
        if user_trade:  # 查询到了有订单
            if user_trade.end >= datetime.datetime.now():  # 一个有没有时区一个有时区不能比较
                nownn = user_trade.end - datetime.datetime.now() + now
            else:
                nownn = now
        else:  # 没买过去
            nownn = now

        tt = re.findall('^\d{13}', str(time.time()).replace('.', ''))[0]  # 获取时间戳毫秒
        if len(user_object.org_id) >= 5:
            id = user_object.org_id[0:5]
            tradeid = str(id) + tt
        else:
            tradeid = str(user_object.org_id) + tt

        time1 = 0

        try:
            number = int(request.GET.get("number"))
            print(number, policy_id)
            if number <= 0:
                return redirect('/web/price/')
            elif policy_id == "1":
                time1 = number * 30
            elif policy_id == "2":
                time1 = number * 30 * 4
            elif policy_id == "3":
                time1 = number * 30 * 12
            else:
                return redirect('/web/price/')
        except Exception:
            return redirect('/web/price/')

        endtime = nownn + datetime.timedelta(days=time1)
        endtime = endtime.strftime("%Y-%m-%d %H:%M:%S")
        """
       # print(endtime.strftime("%Y-%m-%d %H:%M:%S"))  # 时间变成字符串
       
       dd = '2019-03-17 11:00:00'
         dd = datetime.datetime.strptime(dd, "%Y-%m-%d %H:%M:%S")
          print(dd,type(dd)
       字符串到时间
       """

        context = {}

        if policy_id == "1":
            dd = {"org_id": tradeid, "type": "￥10/月", "number": number, "endtime": endtime,
                  "money": 10 * number}

            context = {
                "tradeid": tradeid,  # 订单号
                'money': number * 10,  # 价格
                'policy_id': policy_id,  # 类型
                'number': number,  # 数量
                'end': endtime,  # 到期时间
                "start": now.strftime("%Y-%m-%d %H:%M:%S"),
                "org_id": user_object.org_id,
                "statue": 1,
            }

        elif policy_id == "2":
            dd = {"org_id": tradeid, "type": "￥38/季", "number": number, "endtime": endtime,
                  "money": 38 * number}
            context = {
                "tradeid": tradeid,  # 订单号
                'money': number * 38,  # 价格
                'policy_id': policy_id,  # 类型
                'number': number,  # 数量
                'end': endtime,  # 到期时间
                "start": now.strftime("%Y-%m-%d %H:%M:%S"),
                "org_id": user_object.org_id,
                "statue": 1,
            }


        elif policy_id == "3":
            dd = {"org_id": tradeid, "type": "￥110/年", "number": number, "endtime": endtime,
                  "money": 110 * number}
            context = {
                "tradeid": tradeid,  # 订单号
                'money': number * 110,  # 价格
                'policy_id': policy_id,  # 类型
                'number': number,  # 数量
                'end': endtime,  # 到期时间
                "start": now.strftime("%Y-%m-%d %H:%M:%S"),
                "org_id": user_object.org_id,
                "statue": 1,
            }

        else:
            return redirect('/web/price/')
        print(context)

        conn = get_redis_connection()
        key = 'payment_{}'.format(request.tracer.user.mobile_phone)  # 前缀加用户手机号表示一下
        # conn.set(key, json.dumps(context), nx=60 * 30)
        conn.set(key, json.dumps(context), ex=60 * 1)  # nx参数写错了，应该是ex（表示超时时间） ps：nx=True,表示redis中已存在key，再次执行时候就不会再设置了。
        return render(request, 'web/payment.html', {"dd": dd})

    else:
        return redirect("web/login/")


def pay(request):
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()

    if user_object:  # 没有公司登陆
        conn = get_redis_connection()
        key = 'payment_{}'.format(request.tracer.user.mobile_phone)
        context_string = conn.get(key)
        if not context_string:
            return redirect('web/price/')
        context = json.loads(context_string.decode('utf-8'))
        if context["policy_id"] == "1":
            type = "套餐1：¥ 10/月"
        elif context["policy_id"] == "2":
            type = "套餐2：¥ 38/季"
        elif context["policy_id"] == "3":
            type = "套餐3：¥ 100/年"
        else:
            type = '交易错误'
        # 1. 数据库中生成交易记录（待支付）
        #     等支付成功之后，我们需要把订单的状态更新为已支付、开始&结束时间

        try:  # 防止重复订单
            models.trade.objects.create(  # 订单写入数据库
            tradeid=context['tradeid'],
            org_id=context['org_id'],
            status=1,
            money=context['money'],
            number=int(context['number']),
            type=context['policy_id'],
          )

        except Exception:
           return redirect('web/price/')


        # 生成支付链接

        ali_pay = AliPay(
            appid=settings.ALI_APPID,
            app_notify_url=settings.ALI_NOTIFY_URL,
            return_url=settings.ALI_RETURN_URL,
            app_private_key_path=settings.ALI_PRI_KEY_PATH,
            alipay_public_key_path=settings.ALI_PUB_KEY_PATH
        )
        query_params = ali_pay.direct_pay(
            subject=type,  # 商品简单描述
            out_trade_no=context['tradeid'],  # 商户订单号
            total_amount=context['money']
        )

        pay_url = "{}?{}".format(settings.ALI_GATEWAY, query_params)
        return redirect(pay_url)
    else:
        return redirect('web/login/')

def pay_notify(request):
    """ 支付成功之后触发的URL """

    ali_pay = AliPay(
        appid=settings.ALI_APPID,
        app_notify_url=settings.ALI_NOTIFY_URL,
        return_url=settings.ALI_RETURN_URL,
        app_private_key_path=settings.ALI_PRI_KEY_PATH,
        alipay_public_key_path=settings.ALI_PUB_KEY_PATH
    )

    if request.method == 'GET':  # 支付宝发过来的post，只有在公网ip
        # 只做跳转，判断是否支付成功了，不做订单的状态更新。
        # 支付吧会讲订单号返回：获取订单ID，然后根据订单ID做状态更新 + 认证。
        # 支付宝公钥对支付给我返回的数据request.GET 进行检查，通过则表示这是支付宝返还的接口。
        params = request.GET.dict()
        sign = params.pop('sign', None)  # 踢出singe
        try:
            status = ali_pay.verify(params, sign)  # 比较两个sign是否一样
        except Exception:
            return HttpResponse('非法访问<a href="/web/index/"></a>')

        else:
            if status:

                current_datetime = datetime.datetime.now()

                out_trade_no = params['out_trade_no']
                _object = models.trade.objects.filter(tradeid=out_trade_no).first()

                v = models.trade.objects.filter(org_id=_object.org_id).filter(status="2").order_by(
                    "-crdate").first()  # annotate(Max("crdate"))

                if v:
                    if v.end >= current_datetime:
                        if _object.type == 1:
                            timerr = 30
                        elif _object.type == 2:
                            timerr = 4 * 30
                        elif _object.type == 3:
                            timerr = 12 * 30

                        _object.end = v.end + datetime.timedelta(days=_object.number * timerr)
                else:
                    if _object.type == 1:
                        timerr = 30
                    elif _object.type == 2:
                        timerr = 4 * 30
                    elif _object.type == 3:
                        timerr = 12 * 30
                    _object.end = current_datetime + datetime.timedelta(days=_object.number * timerr)

                _object.start = current_datetime
                _object.status = 2
                _object.save()



                if _object.type == 1:
                    type = "￥10/月"
                elif _object.type == 2:
                    type = "￥38/季"
                elif _object.type == 3:
                    type = "￥110/年"
                else:
                    type = "错误"

                # 获取一下邀请码的状态，如果没有创建邀请码  初始化邀请码表
                invite=models.invite.objects.filter(org_id=_object.org_id).first()
                if invite:
                    invite.end=_object.end #更新邀请码的有效期
                    invite.save()
                else:
                    uid = str(uuid.uuid4())
                    invitestr=uid[0:8]
                    models.invite.objects.create(  # 订单写入数据库
                        org_id=_object.org_id,
                        status=2,#第一次默认未启用
                        number=0,#第一次设置为0
                        end=_object.end,
                        invite=invitestr,
                    )

                # 初始一下，公司问题表
                question=models.question.objects.filter(org_id=_object.org_id).first()
                if question:
                    pass
                else:
                    models.question.objects.create(  # 订单写入数据库
                        org_id=_object.org_id,
                    question1="您自己是否疑似患新型肺炎（隔离中等待医院检验结果）",
                    question2 ="您自己是否确诊患新型肺炎（医院已出具确诊证明）",
                    question3 ="您家人是否疑似患新型肺炎",
                    question4 ="您家人是否确诊患新型肺炎",
                    question5 ="您是否发热（体温大于37.3）",
                    question6 ="您是否有呼吸道感染症状（咳嗽、气促等症状）",
                    question7 ="您是否今日在家",
                    question8 ="您是否接触过疑似或确诊病例",
                    )



                dd = {"org_id": _object.tradeid, "type": type, "number": _object.number, "endtime": _object.end,
                      "money": _object.money, }
                return render(request, 'web/paysuccess.html', {"dd": dd})
            return HttpResponse('支付失败<a href="/web/index/"></a>')
    else:
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        sign = post_dict.pop('sign', None)
        status = ali_pay.verify(post_dict, sign)
        if status:
            current_datetime = datetime.datetime.now()
            out_trade_no = post_dict['out_trade_no']
            _object = models.trade.objects.filter(order=out_trade_no).first()

            _object.status = 2
            _object.start_datetime = current_datetime
            _object.end_datetime = current_datetime + datetime.timedelta(days=365 * _object.count)
            _object.save()
            return HttpResponse('success')

        return HttpResponse('error')


def transaction(request):
    """ 交易记录页面"""
    user_mobile_phone = request.session.get('user_mobile_phone', 0)  # 没有就user_id为0
    # 获取session中的user_id,如果用户登陆了，坑等有，如果没有登陆，就没有

    user_object = models.organization.objects.filter(mobile_phone=user_mobile_phone).first()
    if user_object:  # 没有公司登陆

        user_trade = models.trade.objects.filter(org_id=user_object.org_id).order_by(
            "crdate")  # 查到它所有的订单
        if user_trade:  # 查询到了有订单

            return render(request, 'web/transaction.html', {"user_trade": user_trade})
        else:
            return render(request, 'web/transaction.html', {"user_trade": "True"})
    else:
        return redirect("web/login/")
